﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data;
using Dm.Domain.Repository.Factories;
using Dm.Domain.CrossCutting;
using Dm.Domain.Repository.Exceptions;

namespace Dm.Domain.Repository.RepositoryBase
{
    public abstract class RepositoryBase<TEntity> : IRepositoryBase<TEntity> where TEntity : class
    {
        private IDbSet<TEntity> _dbSet;
        public readonly BaseContext _baseContext;

        public RepositoryBase()
        {
            _baseContext = ContextFactory.Get();
            _dbSet = _baseContext.Set<TEntity>();
        }

        public TEntity Retrieve(int id)
        {
            return _dbSet.Find(id);
        }

        public TEntity Create(TEntity entity)
        {
            entity = _dbSet.Add(entity);
            _baseContext.Commit();
            return entity;
        }

        public void Update(TEntity entity)
        {
            _baseContext.Entry<TEntity>(entity).State = EntityState.Modified;
            _baseContext.SaveChanges();

        }

        public void Delete(TEntity entity)
        {
            _dbSet.Remove(entity);
            _baseContext.SaveChanges();
        }

        public void Delete(int id)
        {
            var entity = _dbSet.Find(id);
            _dbSet.Remove(entity);
            _baseContext.SaveChanges();
        }
    }
}
